import { auth, app, cloudbase, cloudConfig, lib, callCloud } from "./common";

/**
 * 
 * @param {String} type 登录类型，匿名，邮箱登录，微信登录。。。
 */
export async function login(type){
  return new Promise(async (resolve, reject)=>{
    if (type === 'wx' && !cloudConfig.appid) {
      console.warn('如需要获取公众号用户信息，需要配置appid等参数，请参考...')
      type = undefined;
    }
    if (typeof wx !== 'undefined') type = 'wx'
    if (type === 'wx') {
      const provider = auth.weixinAuthProvider({
        appid: cloudConfig.appid,
        scope: cloudConfig.scope
      })
      provider.signInWithRedirect();
      provider.getRedirectResult().then((loginState) => {
        resolve(loginState)
      })
    } else {
      await auth.anonymousAuthProvider().signIn();
      const loginState = await auth.getLoginState();
      resolve(loginState)
    }
  })
}



/**
 * 获取用户信息
 * @param {String} type 登录类型，匿名，邮箱登录，微信登录。。。
 */
export async function getUser(type, cb){

  // 在小程序端
  if (typeof wx !== 'undefined') {
    return minipUser.call(this, type, cb)
  } else {
    // PC 端获取用户
    if (typeof type === 'function') {
      cb = type
      type = undefined
    }
  
    let userEntity = null
    if (auth.currentUser) {
      userEntity = auth.currentUser
    } else {
      const loginState = await login(type)
      if (loginState) userEntity = auth.currentUser
    }
    if (typeof cb === 'function') cb(auth.currentUser)
    return Promise.resolve(userEntity)
  }
}

// 小程序端
// 获取当前小程序用户 instance.getUser().then(res=>{})
// 允许获取非当前的用户信息 instance.getUser({UID: 'xxx'}).then(res=>{})
export async function minipUser(param, cb){
  if (lib.isFunction(param)) {
    cb = param
    param = {}
  }
  return new Promise((resolve, rej)=>{
    if (this.user && !param) {
      if (lib.isFunction(cb)) cb(this.user)
      resolve(this.user)
    } else {
      callCloud(this.baseUrl + '/getUser/', param).then(res=>{
        let result = res.result.data[0]
        if (lib.isFunction(cb)) cb(result)
        resolve(result)
      })
    }
  })
}



/**
 * 更新用户信息
 * @param {Object} param 需要更新的用户信息
 * @param {Function} cb 获取用户信息后的回调方法
 */
export async function updateUser(param={}, cb){
  const user = await getUser()
  return new Promise((resolve, reject) => {
    let userEntity = user
    if (user) {
      user.update(param).then(() => {
        // 更新用户资料成功，刷新用户信息
        user.refresh().then(() => {
          // 刷新后，获取到的用户信息即为最新的信息; const { nickName, gender, avatarUrl } = user;
          userEntity = user
          if (typeof cb === 'function') cb(user)
          resolve(userEntity)
        });
      });
    } else {
      if (typeof cb === 'function') cb(user)
      resolve(userEntity)
    }
  })
}